package com.blue.wechat.invoke.spi.media;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.blue.core.dict.HttpMethod;
import com.blue.wechat.cache.Wechat;
import com.blue.wechat.invoke.BaseInvoker;
import com.blue.wechat.invoke.InvokeException;
import com.blue.wechat.invoke.WechatInvoker;
import com.blue.wechat.invoke.annotation.WechatUrl;
import com.blue.wechat.invoke.model.media.MediaUrl;
import com.blue.wechat.invoke.model.media.UploadMedia;
import com.blue.wechat.invoke.model.media.UploadMediaVideo;

/**
 * 新增永久素材
 * 
 * @author zhengj
 * @since 1.0 2017年6月9日
 */
@WechatUrl(WechatInvoker.ADD_MATERIAL)
public class AddMaterialInvoker extends BaseInvoker<MediaUrl>
{
	public AddMaterialInvoker()
	{
	}

	@Override
	protected WechatInvoker getInvoker()
	{
		return WechatInvoker.ADD_MATERIAL;
	}
	
	@Override
	protected String invoke(String url, HttpMethod method, Object post) throws Exception
	{
		if (!(post instanceof UploadMedia))
			throw new InvokeException("新增永久素材参数类型不是 " + UploadMedia.class.getName());
		
		UploadMedia message = (UploadMedia)post;
		if (message.getType() == null)
			throw new InvokeException("新增永久素材缺少素材类型");
		
		File file = message.getFile();
		Map<String, File> fileParam = new HashMap<>();
		fileParam.put("media", file);
		Map<String, Object> textParam = new HashMap<>();
		if (message.getType() == UploadMedia.Type.VIDEO)
		{
			UploadMediaVideo description = message.getDescription();
			if (description == null)
				throw new InvokeException("新增永久视频素材缺少视频描述信息");
				
			String json = JSON.toJSONString(description);
			textParam.put("description", json);
		}
		String resp = httpInvoker.upload(url, textParam, fileParam);
		return resp;
	}

	@Override
	protected MediaUrl handleSuccess(String resp, Wechat wechat)
	{
		MediaUrl mediaUrl = JSON.parseObject(resp, MediaUrl.class);
		return mediaUrl;
	}
	
	
}
